<template>
  <div id="Params_vue">
    <div class="toolbar">
      <el-form inline @submit.native.prevent>
        <el-form-item>
          <el-input :placeholder="'请输入关键字 ( ' + tableParam.dropdown[tableParam.keycurrent].value + ' )'" v-model="tableParam._keyword" size="mini"></el-input>
        </el-form-item>
        <el-form-item>
          <el-dropdown split-button="" type="primary" @command="updateKeyCurrent" @click="tableParam.keyword = tableParam._keyword; tableParam.pageno = 1; query();" size="mini">
            <i class="el-icon-search" style="margin-right:5px;"></i>查询
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="item in tableParam.dropdown" :command="item.key" :key="item.key + '_dropdown'">{{item.value}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button type="primary" icon="el-icon-plus" @click="recordFormInit(); recordForm.visible = true; recordForm.flag = true;" size="mini">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-alert title="谨慎操作，尽量避免删除或修改正在使用的参数" type="warning" :show-icon="true" style="line-height:20px; padding-right:25px;"></el-alert>
        </el-form-item>
      </el-form>
    </div>
    <sample-table :data="records" :isloading="tableParam.loading" sortcustom @afterSortChange="sortChange" @selectionChange="selectionChange">
      <sample-table-header slot="header">
        <sample-table-header-selection />
        <sample-table-header-column label="键 key" prop="ZK_KEY" sortable />
        <sample-table-header-column label="值 value" prop="ZK_VALUE" sortable />
        <sample-table-header-column label="描述" prop="ZK_DESC" sortable />
        <sample-table-header-column label="创建时间" prop="EB_CREATE_DATETIME" sortable />
        <sample-table-header-column label="最后修改" prop="EB_LASTMODIFY_DATETIME" sortable />
        <sample-table-header-column label="操作" />
      </sample-table-header>
      <sample-table-body slot-scope="scope" :row="scope.row" :index="scope.index" slot="body">
        <sample-table-body-selection />
        <sample-table-body-column prop="ZK_KEY" />
        <sample-table-body-column prop="ZK_VALUE" />
        <sample-table-body-column prop="ZK_DESC" />
        <sample-table-body-column>
          {{$common.ChangeDateFormat_hhmmss(scope.row.EB_CREATE_DATETIME, '-')}}
        </sample-table-body-column>
        <sample-table-body-column>
          {{$common.ChangeDateFormat_hhmmss(scope.row.EB_LASTMODIFY_DATETIME, '-')}}
        </sample-table-body-column>
        <sample-table-body-column>
          <i class="el-icon-edit icon-btn-edit" @click="recordFormInit(); getRecord(scope)"></i>
          <i class="el-icon-delete icon-btn-del" @click="delRecord(scope)"></i>
        </sample-table-body-column>
      </sample-table-body>
    </sample-table>
    <el-col :span="24" class="botton_toolbar">
      <el-button type="danger" :disabled="selection.length === 0" icon="el-icon-delete" @click="batchDelete" size="mini">
        批量删除<span v-if="selection.length !== 0"> (共{{selection.length}}条)</span>
      </el-button>
      <el-pagination layout="prev, pager, next, jumper, total" :page-size="tableParam.pagesize" :current-page="tableParam.pageno" :total="tableParam.total" @current-change="currentChange" style="float:right;">
      </el-pagination>
    </el-col>
    <el-dialog :title="recordForm.flag ? '新增' : '编辑'" :visible.sync="recordForm.visible">
      <el-form ref="recordForm" class="recordForm" label-width="80px" :model="recordForm.record" :rules="recordformRules" @submit.native.prevent>
        <el-form-item label="　键　" prop="ZK_KEY">
          <el-input v-model="recordForm.record.ZK_KEY" placeholder="请输入键(只允许数字与英文)" :disabled="!recordForm.flag"></el-input>
        </el-form-item>
        <el-form-item label="　值　" prop="ZK_VALUE">
          <el-input v-model="recordForm.record.ZK_VALUE" placeholder="请输入值"></el-input>
        </el-form-item>
        <el-form-item label="描　述" prop="ZK_DESC">
          <el-input v-model="recordForm.record.ZK_DESC" placeholder="请输入描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="recordForm.visible = false;">取 消</el-button>
        <el-button type="primary" @click="recordForm.flag ? insertRecord() : updateRecord()">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selection: [],
      records: [],
      tableParam: {
        keyword: '',
        _keyword: '',
        prop: '',
        order: '',
        pagesize: 100,
        pageno: 1,
        total: 0,
        loading: false,
        dropdown: [
          { key: 'ZK_KEY', value: '键' },
          { key: 'ZK_VALUE', value: '值' },
          { key: 'ZK_DESC', value: '描述' },
        ],
        keycurrent: 0,
      },
      recordForm: {
        flag: true,
        record: {
          ZK_ID: '',
          ZK_KEY: '',
          ZK_VALUE: '',
          ZK_DESC: '',
        },
        visible: false,
        index: -1,
      },
      recordformRules: {
        ZK_KEY: [{ required: true, message: '请输入键', trigger: 'blur' }],
        ZK_VALUE: [{ required: true, message: '请输入值', trigger: 'blur' }],
        ZK_DESC: [{ required: true, message: '请输入描述', trigger: 'blur' }],
      },
    };
  },
  created() {
    this._recordForm = JSON.stringify(this.recordForm);
    this.query();
  },
  methods: {
    query() {
      this.tableParam.loading = true;
      this.$http
        .get(
          '/api/param/list',
          {
            params: {
              KEYWORD: this.tableParam.keyword,
              TYPE: this.tableParam.dropdown[this.tableParam.keycurrent].key,
              PROP: this.tableParam.prop,
              ORDER: this.tableParam.order,
              PAGESIZE: this.tableParam.pagesize,
              PAGENO: this.tableParam.pageno,
            },
          },
          { emulateJSON: true },
        )
        .then(res => {
          this.tableParam.loading = false;
          if (res.data.flag === 'True') {
            this.tableParam.total = Number.parseInt(res.data.message, 10);
            this.records = res.data.result;
          }
        });
    },
    updateKeyCurrent(command) {
      this.tableParam.dropdown.forEach((item, index) => {
        if (item.key === command) {
          this.tableParam.keycurrent = index;
        }
      });
    },
    selectionChange(sels) {
      const list = [];
      sels.forEach(item => {
        list.push(this.records[item]);
      });
      this.selection = list;
    },
    recordFormInit() {
      if (this.$refs.recordForm) {
        this.$refs.recordForm.resetFields();
      }
      this.recordForm = JSON.parse(this._recordForm);
    },
    currentChange(currentPage) {
      if (this.tableParam.pageno !== currentPage) {
        this.tableParam.pageno = currentPage;
        this.query();
      }
    },
    sortChange(s) {
      if (s.sortOrder) {
        this.tableParam.prop = s.sortProp;
        this.tableParam.order = s.sortOrder.includes('desc')
          ? 'descending'
          : 'ascending';
        this.tableParam.pageno = 1;
        this.query();
      }
    },
    delRecord(scope) {
      this.$confirm(
        '谨慎操作，该删除可能带来不可逆后果，请确保该参数的有效性',
        '参数删除提醒',
        { type: 'warning' },
      )
        .then(() => {
          this.$http
            .post('/api/param/detail', { IDS: scope.row.ZK_ID })
            .then(res => {
              if (res.data.flag === 'True') {
                this.records.splice(scope.index, 1);
                this.$notify({
                  title: '成功',
                  message: '已成功删除一条记录',
                  type: 'success',
                });
              }
            });
        })
        .catch(() => {});
    },
    batchDelete() {
      const ids = [];
      if (this.selection.length === 0) {
        this.$message.error('请先选中需要删除的选项');
        return;
      }
      this.selection.forEach(item => {
        ids.push(item.ZK_ID);
      });
      this.$confirm(
        '谨慎操作，该删除可能带来不可逆后果，请确保该参数的有效性',
        '参数删除提醒',
        { type: 'warning' },
      )
        .then(() => {
          this.$http
            .post('/api/param/detail', { IDS: ids.join(',') })
            .then(res => {
              if (res.data.flag === 'True') {
                this.$notify({
                  title: '成功',
                  message: '成功删除多条记录(一秒后将自动刷新页面)',
                  type: 'success',
                });
                setTimeout(() => {
                  window.location.reload();
                }, 500);
              }
            });
        })
        .catch(() => {});
    },
    getRecord(scope) {
      this.$http
        .get('/api/param/detail', {
          params: { UID: scope.row.ZK_ID },
        })
        .then(res => {
          if (res.data.flag === 'True') {
            this.recordForm.record = res.data.result;
            this.recordForm.flag = false;
            this.recordForm.visible = true;
            this.recordForm.index = scope.index;
          }
        });
    },
    insertRecord() {
      this.$refs.recordForm.validate(valid => {
        if (valid) {
          this.$http
            .post('/api/param/insert', this.recordForm.record)
            .then(res => {
              if (res.data.flag === 'True') {
                this.records.unshift(
                  JSON.parse(JSON.stringify(this.recordForm.record)),
                );
                this.$notify({
                  title: '成功',
                  message: '新增成功(一秒后将自动刷新页面)',
                  type: 'success',
                });
                this.recordFormInit();
                setTimeout(() => {
                  window.location.reload();
                }, 500);
              }
            });
        } else {
          this.$message.warning('请验证数据有效性');
        }
      });
    },
    updateRecord() {
      this.$refs.recordForm.validate(valid => {
        if (valid) {
          this.$http
            .post('/api/param/update', this.recordForm.record)
            .then(res => {
              if (res.data.flag === 'True') {
                const form = JSON.parse(JSON.stringify(this.recordForm.record));
                this.records[this.recordForm.index].ZK_KEY = form.ZK_KEY;
                this.records[this.recordForm.index].ZK_DESC = form.ZK_DESC;
                this.records[this.recordForm.index].ZK_VALUE = form.ZK_VALUE;
                this.$notify({
                  title: '成功',
                  message: '更新参数成功',
                  type: 'success',
                });
                this.recordFormInit();
              }
            });
        } else {
          this.$message.warning('请验证数据有效性');
        }
      });
    },
  },
};
</script>

<style>
#Params_vue .botton_toolbar {
  border: 1px solid #f2f2f2;
  box-shadow: 0 0 5px #f2f2f2;
  padding: 10px;
  margin: 10px 0 20px 0;
}
#Params_vue .botton_toolbar:hover {
  background: #f2f2f2;
  box-shadow: none;
}
</style>
